<template>
	<!-- 登录页面 -->
	<view class="login-page">
		<!-- 顶部蓝色区域 -->
		<view class="header-section">
			<view class="header-content">
				<view class="greeting-text">
					<text class="greeting-title">您好,</text>
					<text class="greeting-subtitle">欢迎登录车联网服务!</text>
				</view>
				<!-- 插画区域占位 -->
				<view class="illustration-area"></view>
			</view>
		</view>

		<!-- 插画图片 - 独立层级 -->
		<view class="illustration-container">
			<image src="/static/login/组 6@3x.png" mode="aspectFit" class="illustration-image"></image>
		</view>

		<!-- 登录表单卡片 -->
		<view class="login-card-wrapper">
			<view class="login-card">
				<view class="input-group">
					<input class="input-field" v-model="phoneNumber" placeholder="手机号登陆" type="number" maxlength="11" />
					<view class="input-line"></view>
				</view>
				<view class="input-group">
					<input class="input-field code-input" v-model="verificationCode" placeholder="输入验证码" type="number"
						maxlength="6" />
					<button class="get-code-btn" :disabled="codeButtonDisabled" @click="getVerificationCode">
						{{ codeButtonText }}
					</button>
					<view class="input-line"></view>
				</view>
				<button class="login-btn" @click="handleLogin">登录</button>
			</view>
		</view>

		<!-- 位置权限弹窗 -->
		<view class="location-modal" v-if="showLocationModal" @click.stop>
			<view class="modal-content" @click.stop>
				<view class="modal-title">获取你的位置信息</view>
				<view class="modal-desc">你的位置信息将用于获取你附近的站点</view>
				<view class="modal-buttons">
					<button class="modal-btn reject-btn" @click="handleRejectLocation">拒绝</button>
					<button class="modal-btn allow-btn" @click="handleAllowLocation">允许</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		saveLocation
	} from '@/utils/location.js'

	// 表单数据
	const phoneNumber = ref('')
	const verificationCode = ref('')

	// 验证码按钮
	const codeButtonDisabled = ref(false)
	const codeButtonText = ref('获取验证码')
	let countdownTimer = null
	let countdown = 60

	// 位置权限弹窗
	const showLocationModal = ref(false)

	// 页面加载时显示位置权限弹窗
	onLoad(() => {
		// 检查是否已经授权过位置
		uni.getSetting({
			success: (res) => {
				if (!res.authSetting['scope.userLocation']) {
					// 未授权，显示弹窗
					setTimeout(() => {
						showLocationModal.value = true
					}, 500)
				} else {
					// 已授权，直接获取位置
					getUserLocation()
				}
			},
			fail: () => {
				// 获取设置失败，显示弹窗
				setTimeout(() => {
					showLocationModal.value = true
				}, 500)
			}
		})
	})

	// 获取验证码
	const getVerificationCode = () => {
		if (!phoneNumber.value || phoneNumber.value.length !== 11) {
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'none'
			})
			return
		}

		// 开始倒计时
		codeButtonDisabled.value = true
		countdown = 60
		codeButtonText.value = `${countdown}秒后重新获取`

		countdownTimer = setInterval(() => {
			countdown--
			if (countdown > 0) {
				codeButtonText.value = `${countdown}秒后重新获取`
			} else {
				codeButtonDisabled.value = false
				codeButtonText.value = '获取验证码'
				clearInterval(countdownTimer)
			}
		}, 1000)

		// 这里调用获取验证码的API
		uni.showToast({
			title: '验证码已发送',
			icon: 'success'
		})
	}

	// 拒绝位置权限
	const handleRejectLocation = () => {
		showLocationModal.value = false
		uni.showToast({
			title: '位置权限已拒绝',
			icon: 'none'
		})
	}

	// 允许位置权限
	const handleAllowLocation = () => {
		showLocationModal.value = false
		// 直接尝试获取位置，uni.getLocation 会自动处理权限请求
		getUserLocation()
	}

	// 获取用户位置
	const getUserLocation = () => {
		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				console.log('获取位置成功：', res)
				// 逆地理编码获取地址信息
				reverseGeocode(res.latitude, res.longitude)
			},
			fail: (err) => {
				console.error('获取位置失败：', err)
				uni.showToast({
					title: '获取位置失败',
					icon: 'none'
				})
			}
		})
	}

	// 逆地理编码（根据经纬度获取地址）
	const reverseGeocode = (latitude, longitude) => {
		// 使用腾讯地图API进行逆地理编码
		const key = 'EJABZ-ZBULT-UFMXD-VT6JM-I37RS-OZFVN'
		const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}&get_poi=1`

		uni.request({
			url: url,
			method: 'GET',
			success: (res) => {
				if (res.statusCode === 200 && res.data.status === 0) {
					const result = res.data.result
					const locationData = {
						latitude: latitude,
						longitude: longitude,
						address: result.address || '',
						city: result.address_component?.city || '',
						province: result.address_component?.province || '',
						district: result.address_component?.district || ''
					}
					// 保存位置信息
					saveLocation(locationData)
				}
			},
			fail: (err) => {
				console.error('逆地理编码失败：', err)
				// 即使逆地理编码失败，也保存经纬度
				saveLocation({
					latitude: latitude,
					longitude: longitude,
					address: '',
					city: '',
					province: '',
					district: ''
				})
			}
		})
	}

	// 登录
	const handleLogin = () => {
		if (!phoneNumber.value || phoneNumber.value.length !== 11) {
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'none'
			})
			return
		}

		if (!verificationCode.value) {
			uni.showToast({
				title: '请输入验证码',
				icon: 'none'
			})
			return
		}

		// 这里调用登录API
		uni.showLoading({
			title: '登录中...'
		})

		// 模拟登录
		setTimeout(() => {
			uni.hideLoading()
			// 保存登录状态
			uni.setStorageSync('isLogin', true)
			uni.setStorageSync('phoneNumber', phoneNumber.value)

			// 登录成功后跳转到定位选择页面
			uni.navigateTo({
				url: '/pages/login/Positioning/Positioning',
				success: () => {
					uni.showToast({
						title: '登录成功',
						icon: 'success'
					})
				}
			})
		}, 1500)
	}
</script>

<style scoped>
	.login-page {
		min-height: 100vh;
		background-color: #f5f5f5;
		position: relative;
	}

	/* 顶部蓝色区域 */
	.header-section {
		/* background: linear-gradient(135deg, #2575fc 0%, #6a11cb 100%); */
		background: url(/static/login/组 8.png) no-repeat center top;
		background-size: cover;
		padding: 80rpx 40rpx 60rpx;
		position: relative;
		overflow: visible;
		padding-bottom: 100rpx;
		z-index: 100;
	}

	.header-section::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		/* background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 120"><path d="M0,60 Q300,20 600,60 T1200,60 L1200,0 L0,0 Z" fill="rgba(255,255,255,0.1)"/></svg>') repeat-x; */
		opacity: 0.3;
	}

	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		position: relative;
		z-index: 1;
		height: 100%;
		overflow: visible;
	}

	.greeting-text {
		display: flex;
		flex-direction: column;
		flex: 1;
	}

	.greeting-title {
		font-size: 56rpx;
		font-weight: bold;
		color: #fff;
		line-height: 80rpx;
		margin-bottom: 16rpx;
	}

	.greeting-subtitle {
		font-size: 32rpx;
		color: #fff;
		line-height: 48rpx;
		opacity: 0.9;
	}

	.illustration-area {
		width: 300rpx;
		height: 400rpx;
		position: relative;
		align-self: flex-end;
	}

	/* 插画容器 - 独立定位，确保在最上层 */
	.illustration-container {
		position: absolute;
		top: 150rpx;
		right: 20rpx;
		width: 300rpx;
		height: 450rpx;
		z-index: 1000;
		pointer-events: none;
		display: flex;
		align-items: flex-start;
		justify-content: flex-end;
	}

	.illustration-image {
		width: 100%;
		height: 100%;
		object-fit: contain;
		display: block;
		transform: translateY(0);
	}

	.illustration-text {
		font-size: 120rpx;
	}

	/* 登录表单卡片容器 */
	.login-card-wrapper {
		position: relative;
		z-index: 100;
		margin-top: -40rpx;
		top: -100rpx;
	}

	/* 登录表单卡片 */
	.login-card {
		background-color: #fff;
		border-radius: 32rpx 32rpx 0 0;
		padding: 60rpx 40rpx 40rpx;
		padding-top: 120rpx;
		position: relative;
		z-index: 100;
		min-height: calc(100vh - 400rpx);
	}

	.input-group {
		position: relative;
		margin-bottom: 40rpx;
	}

	.input-field {
		width: 100%;
		height: 88rpx;
		font-size: 32rpx;
		color: #333;
		padding: 0 20rpx;
		background-color: transparent;
	}

	.code-input {
		padding-right: 180rpx;
	}

	.input-line {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 1rpx;
		background-color: #e5e5e5;
	}

	.get-code-btn {
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		background-color: #2575fc;
		color: #fff;
		border-radius: 40rpx;
		padding: 12rpx 24rpx;
		font-size: 24rpx;
		border: none;
		line-height: 1;
	}

	.get-code-btn[disabled] {
		background-color: #ccc;
		color: #999;
	}

	.login-btn {
		width: 100%;
		height: 96rpx;
		background: linear-gradient(90deg, #2575fc, #6a11cb);
		color: #fff;
		border-radius: 48rpx;
		font-size: 36rpx;
		font-weight: bold;
		border: none;
		margin-top: 60rpx;
	}

	/* 位置权限弹窗 */
	.location-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: flex-end;
		justify-content: center;
		z-index: 9999;
		padding: 0 40rpx 60rpx;
	}

	.modal-content {
		width: 100%;
		background-color: #fff;
		border-radius: 24rpx;
		padding: 40rpx 30rpx 30rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
	}

	.modal-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		text-align: center;
	}

	.modal-desc {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 40rpx;
		text-align: center;
		line-height: 40rpx;
	}

	.modal-buttons {
		display: flex;
		gap: 20rpx;
	}

	.modal-btn {
		flex: 1;
		height: 88rpx;
		border-radius: 44rpx;
		font-size: 32rpx;
		border: none;
	}

	.reject-btn {
		background-color: #f5f5f5;
		color: #666;
	}

	.allow-btn {
		background-color: #2575fc;
		color: #fff;
	}
</style>